import Taro from '@tarojs/taro'

import {getJSON, postJSON} from '../utils'
import apiObj from '../api'
import {
  GET_TOPIC_LIST, 
  GET_TOPIC_NEXT_LIST, 
  GET_TOPIC_INFO_CONTENT,
  PLAY_TOPIC_NICE
} from '../constants/topicList'

/**
 * action creator
 * @param {*} data 
 */
export const getTopicList = (data) => {
  return {
    type: GET_TOPIC_LIST,
    currentTabList: data
  }
}

export const getTopicNextList = (data, params) => {
  return {
    type: GET_TOPIC_NEXT_LIST,
    currentTabList: data,
    page: params.page
  }
}

export const getTopicInfoContent = (data) => {
  return {
    type: GET_TOPIC_INFO_CONTENT,
    getTopicInfoContent: data
  }
}

export const playTopicNice = () => {
  return {
    type: PLAY_TOPIC_NICE
  }
}

/**
 * dispatch action
 * @param {*} params 
 */
export function getTopicListAction(params){
  return async dispatch => {
    let result = await getJSON(apiObj.getTopic, params)
    if(result && result.data){
      if(result.data.success){
        let data = result.data.data
        dispatch(getTopicList(data))
      }
    }
  }
}

export function getTopicNextListAction(params){
  return async dispatch => {
    let result = await getJSON(apiObj.getTopic, params)
    if(result && result.data && result.data.success){
      let data = result.data.data 
      if(data.length > 0){
        dispatch(getTopicNextList(data, params))
      }
    }
  }
}

export function getTopicInfoAction(params){
  return async dispatch => {
    let result = await getJSON(apiObj.getTopicInfo + params.id, params)
    if(result && result.data && result.data.success){
      let data = result.data.data
      dispatch(getTopicInfoContent(data))
    }else{
      console.error('request topic info fail!')
    }
  }
}

export function playTopicNiceAction(params){
  return async dispatch => {
    let result = await postJSON(apiObj.agreeTopic + params.replyid + '/ups', params)
    if(result && result.data && result.data.success){
      dispatch(playTopicNice())
    }else{
      Taro.showToast({title: '点赞失败!', icon: 'none'})
    }
  }
}

export async function replyModalText(params){
  let result = await postJSON(apiObj.replyTopic + params.topicid + '/replies', params)
  if(result && result.data && result.data.success){
    return result.data
  }else{
    Taro.showToast({title: '评论失败!', icon: 'none'})
  }
}

export async function editTopic(params){
  console.log(params)
  let result = await postJSON(apiObj.updateTopic, params)
  if(result && result.data && result.data.success){
    return result.data
  }else{
    Taro.showToast({title: '更新话题失败', icon: 'none'})
  }
}